/*
 * @Author: Setsuna
 * @Email: setsuna.xyz@qq.com
 * @FilePath: \src\pages\StatementOfAccount\StatementOfAccountRecord\Confirmed\index.tsx
 * @Date: 2022-03-16 09:22:01
 * @LastEditTime: 2023-05-08 16:38:57
 */

import React from 'react'
import {
  UdTable,
  UdFilter,
  columnRenders,
  UdDrawer,
  UdModal,
  IUdColumn,
  UdDateRangePicker,
  http,
  UdToolbar,
} from '@/lib'
import { Badge, Button, message, Select, Tooltip } from 'antd'
import { WrappedFormUtils } from 'antd/lib/form/Form'
import ConfirmedRecordDetail from './detail'
import apis from '@/apis/StatementOfAccount'
import {
  compressAndDownload,
  dataRange,
  downBlobFile,
  handDownload,
  matchFileSuffixType,
  transformSearchValue,
} from '@/utils/methods'
import moment from 'moment'
import PhotoView from '@/components/PhotoViewSimple'
import UdSelect from '@/components/UdFormControls/UdSelect'
import udMainStore from '@/store/UdMain'
import dayjs from 'dayjs'
const { Option } = Select
interface FileRecord {
  id: number
  letterName: string
  modelUrl: string
  replyUrl: string
  letterLaunchId: number
  brandCode: string
  dealerCode: string
  [key: string]: any
}

const RESULT_STATUS = {
  WRONG: '信息不符',
  RIGHT: '信息无误',
}
export default class ConfirmedList extends React.PureComponent<any> {
  public brandList = udMainStore.brandList

  protected filterForm: WrappedFormUtils = {} as WrappedFormUtils
  state = {
    visible: false,
    images: [],
    searchValues:{
      brandCode:this.brandList[0].value
    },
    selectedRowKeys: [],
    selectedRows: [],
    dataSource: [],
    page: 1,
    size: 10,
    total: 0,
    loading: false,
    conditions: [
      {
        label: '品牌公司',
        id: 'brandCode',
        initialValue: this.brandList[0].value,
        render: <UdSelect showSearch allowClear={false} options={this.brandList} />,
      },
      {
        label: '经销商',
        id: 'dealerName',
      },
      {
        id: 'dealerCode',
        label: '经销商编码',
      },
      {
        id: 'replyConclusionOn',
        label: '回函结论',
        render: (
          <Select>
            <Option value="RIGHT">信息无误</Option>
            <Option value="WRONG">信息不符</Option>
          </Select>
        ),
      },
      {
        id: ['confirmTimeBeg', 'confirmTimeEnd'],
        label: '确认时间',
        render: () => (
          <UdDateRangePicker
            ranges={dataRange}
            valueFormat={['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59']}
            disabledDate={current => {
              return current && current.isAfter(moment().format('YYYY-MM-DD'), 'day')
            }}
          />
        ),
      },
    ],
  }
  columns: IUdColumn<any>[] = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      width: '50px',
      render: (text, reoled, index) => index + 1,
    },
    { title: '经销商编码', dataIndex: 'dealerCode', key: 'dealerCode', minWidth: '160px' },
    { title: '经销商名称', dataIndex: 'dealerName', key: 'dealerName', minWidth: '160px' },
    { title: '对账函名称', dataIndex: 'letterName', key: 'letterName', minWidth: '150px' },
    {
      title: '截止时间',
      dataIndex: 'sendTime',
      key: 'sendTime',
      minWidth: '90',
      render: (text, record) => {
        return (
          <Tooltip title={dayjs(record.sendTime).format('YYYY-MM-DD')}>
            <div style={{ width: '200px', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
              {dayjs(record.sendTime).format('YYYY-MM-DD')}
            </div>
          </Tooltip>
        )
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      minWidth: '110px',
      render: (text, record) => {
        return (
          <Tooltip title={record.createTime}>
            <div style={{ width: '200px', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
              {record.createTime}
            </div>
          </Tooltip>
        )
      },
    },
    {
      title: '回函时间',
      dataIndex: 'replyTime',
      key: 'replyTime',
      minWidth: '110px',
      render: (text, record) => {
        return (
          <Tooltip title={record.replyTime}>
            <div style={{ width: '200px', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
              {record.replyTime}
            </div>
          </Tooltip>
        )
      },
    },
    {
      title: '确认时间',
      dataIndex: 'confirmTime',
      key: 'confirmTime',
      minWidth: '110px',
      render: (text, record) => {
        return (
          <Tooltip title={record.confirmTime}>
            <div style={{ width: '200px', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
              {record.confirmTime}
            </div>
          </Tooltip>
        )
      },
    },
    {
      title: '回函结论',
      dataIndex: 'replyConclusionOn',
      key: 'replyConclusionOn',
      minWidth: '110px',
      render: (text, record) => {
        return (
          <span>
            <Badge status={text === 'RIGHT' ? 'success' : 'error'} />
            {RESULT_STATUS[text]}
          </span>
        )
      },
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      fixed: 'right' as 'right',
      width: 130,
      render: columnRenders.operate([
        {
          title: '查看',
          action: (text: any, record: any) => this.showRecordDetail(record),
        },
        {
          title: '预览',
          action: (text: any, record: any) => this.handFileView(record),
        },
        {
          title: '下载',
          action: (text: any, record: any) => void handDownload(record.replyUrl),
        },
      ]),
    },
  ]

  render() {
    let { selectedRowKeys = [], visible, images } = this.state
    return (
      <>
        <PhotoView
          visible={visible}
          onClose={() => {
            this.setState({ visible: false })
          }}
          images={images}
        />
        <UdFilter
          getForm={form => {
            this.filterForm = form
          }}
          items={this.state.conditions}
          onSearch={values => {
            this.handleSearch(values)
          }}
          loading={this.state.loading}
          resetAfter={this.resetFilterHandle}
        />
        <UdToolbar
          other={
            <>
              <Button
                type="primary"
                style={{ marginRight: 10 }}
                onClick={() => {
                  this.handBatchDownload()
                }}
              >
                下载附件({selectedRowKeys.length})
              </Button>
              <Button
                type="primary"
                style={{ marginRight: 10 }}
                onClick={() => {
                  this.handExport()
                }}
              >
                导出
              </Button>
            </>
          }
        ></UdToolbar>
        <UdTable
          rowKey="id"
          loading={this.state.loading}
          columns={this.columns}
          dataSource={this.state.dataSource}
          onChange={this.handleChangePage}
          rowSelection={{ onChange: this.onSelectChange, onSelectAll: this.onSelectAll, selectedRowKeys }}
          scroll={{ x: true }}
          pagination={{
            current: this.state.page,
            pageSize: this.state.size,
            total: this.state.total,
            showQuickJumper: true,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '30', '40','100'],
            showTotal: (total, range) => `共${total}项，当前${range[0]}-${range[1]}项`,
          }}
        ></UdTable>
      </>
    )
  }

  private onSelectAll = (selected, selectedRows, changeRows) => {
    if (selected) {
      const { dataSource } = this.state
      this.setState({ selectedRows: dataSource, selectedRowKeys: dataSource.map(({ id }) => id) })
    } else {
      this.setState({ selectedRows: [], selectedRowKeys: [] })
    }
  }

  private onSelectChange = (selectedRowKeys: number[], selectedRows: any[]) => {
    console.log('selectedRowKeys', selectedRowKeys)
    this.setState({ selectedRowKeys, selectedRows })
  }

  public componentDidMount() {
    this.getRecordTableData()
  }

  private handExport = ()=>{
    this.setState({ downloading: true })
    let params = this.state.searchValues
    http
      .post(apis.downloadReconciliationHistoryExcel, { ...params,type:1 }, { responseType: 'arraybuffer' })
      .then(res => {
        if (!res.data.code) {
          downBlobFile(res.data, `对账函记录-财务已确认`)
        }
      })
      .finally(() => {
        this.setState({ downloading: false })
      })
  }

  private handBatchDownload = () => {
    let { selectedRowKeys = [], selectedRows = [] } = this.state
    if (selectedRowKeys.length > 0) {
      compressAndDownload({
        data: selectedRows,
        downloadFileName: '对账函记录-财务已确认-附件' + Date.now(),
        urlKey: 'replyUrl',
        nameKey: 'letterName',
      })
    }
  }

  private handFileView = (record: FileRecord): void => {
    const rex = /^(((ht|f)tps?):\/\/)?([^!@#$%^&*?.\s-]([^!@#$%^&*?.\s]{0,63}[^!@#$%^&*?.\s])?\.)+[a-z]{2,6}\/?/
    let { replyFileName: fileName, replyUrl: fileUrl } = record
    if (rex.test(fileUrl)) {
      let result = matchFileSuffixType(fileUrl)
      if (result === 'word' || result === 'excel') {
        fileUrl = `https://view.officeapps.live.com/op/view.aspx?src=${fileUrl}`
        this.showFileViewModal(fileName, fileUrl)
      } else if (result === 'pdf') {
        this.showFileViewModal(fileName, fileUrl)
      } else if (result === 'image') {
        this.setState({ visible: true, images: [fileUrl] })
      }
    } else {
      message.error('附件URL无效')
    }
  }

  private showFileViewModal = (fileName: string, fileUrl: string) => {
    UdModal.open({
      title: fileName,
      width: '80%',
      bodyStyle: { padding: '0' },
      content: (
        <div style={{ height: '700px', overflow: 'hidden' }}>
          <iframe
            title={fileName}
            src={fileUrl}
            width="100%"
            height="100%"
            frameBorder="0"
            style={{ border: 'none' }}
            seamless
          ></iframe>
        </div>
      ),
      footer: null,
    })
  }

  private showRecordDetail = (record: FileRecord): void => {
    UdDrawer.open({
      title: '已确认详情',
      width: '50%',
      content: <ConfirmedRecordDetail record={record} />,
    })
  }

  private handleChangePage = pagination => {
    const { current: page, pageSize: size } = pagination
    this.setState({ page, size }, () => {
      this.getRecordTableData()
    })
  }

  private handleSearch = (values: object) => {
    this.setState({ searchValues: {...transformSearchValue(values)}, dataSource: [],selectedRowKeys:[],selectedRows:[], page: 1, total: 0 }, () => {
      this.getRecordTableData()
    })
  }

  private resetFilterHandle = (form: WrappedFormUtils) => {
    this.setState({ searchValues: {...transformSearchValue(form.getFieldsValue())},dataSource: [],selectedRowKeys:[],selectedRows:[], page: 1, total: 0 }, () => {
      this.getRecordTableData()
    })
  }
  private getRecordTableData = async () => {
    this.setState({ loading: true })
    try {
      let list: any = await http.post(apis.getReconciliationHistoryList, {
        page: this.state.page,
        size: this.state.size,
        conditions: { ...this.state.searchValues, type: 1 },
      })
      const dataSource = list.data?.content
      this.setState({
        dataSource,
        total: list.data.totalElements,
        loading: false,
      })
    } catch (error) {
      this.setState({
        loading: false,
      })
    }
  }
}
